package com.aaa.member.controller;

import com.aaa.common.constants.ExceptionConstant;
import com.aaa.common.constants.ReturnCode;
import com.aaa.common.util.CustomException;
import com.aaa.common.util.Result;
import com.aaa.member.entity.TbMember;
import com.aaa.member.service.TbMemberService;
import com.aaa.member.util.ExcelUtil;
import com.aaa.member.util.TestSms;
import org.apache.shiro.crypto.hash.Sha512Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * (TbMember)表控制层
 *
 * @author LiangLei
 * @since 2020-11-18 18:37:02
 */
@RestController
@RequestMapping("tbMember")
public class TbMemberController {
    /**
     * 服务对象
     */
    @Resource
    private TbMemberService tbMemberService;

    @Autowired
    private TestSms testSms;

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("selectOne")
    public Result selectOne(Integer id) {
        if(id==null){
            throw new CustomException(ExceptionConstant.INVALID_ARGUMENT.getErrorCode(),
                    ExceptionConstant.INVALID_ARGUMENT.getErrorMessage());
        }

        return new Result(ReturnCode.SUCCESSS.getCode(), ReturnCode.SUCCESSS.getMsg()
                ,this.tbMemberService.queryById(id));
    }

    /**
     *  分页
     */
    @GetMapping("queryPageByParam")
    Result queryPageByParam(Integer pageNo, Integer pageSize, TbMember tbMember){
        return this.tbMemberService.queryPageByParam(pageNo,pageSize,tbMember);
    }



    @PostMapping("add")
    public Result add(TbMember tbMember,String code){
        //返回成功
        String salt = "efdd1d36-2430-4";
        tbMember.setPwSalt(salt);
        String password = tbMember.getPassword();
        Sha512Hash sha512Hash = new Sha512Hash(password,salt,1024);
        System.out.println(sha512Hash.toString());
        tbMember.setPassword(sha512Hash.toString());
        System.out.println(code+"接地参数");
        System.out.println(redisTemplate.opsForValue().get("code"));
        if(redisTemplate.opsForValue().get("code").equals(code)){
            return new Result(ReturnCode.SUCCESSS.getCode(),
                    ReturnCode.SUCCESSS.getMsg(),this.tbMemberService.insert(tbMember));
        }else {
            return new Result(ReturnCode.FAIL.getCode(),
                    ReturnCode.FAIL.getMsg(),"验证码不正确");
        }

    }


    @DeleteMapping("deleteMenu")
    public Result deleteMenu(Integer id){
        //返回成功
        return new Result(ReturnCode.SUCCESSS.getCode(),
                ReturnCode.SUCCESSS.getMsg(),this.tbMemberService.deleteById(id));
    }

    @DeleteMapping("delete")
    public Result delete(Integer id){
        //返回成功
        return new Result(ReturnCode.SUCCESSS.getCode(),
                ReturnCode.SUCCESSS.getMsg(),this.tbMemberService.deleteById(id));
    }

    @PutMapping("updateMenu")
    public Result updateMenu(@RequestBody TbMember tbMember){
        //返回成功
        return new Result(ReturnCode.SUCCESSS.getCode(),
                ReturnCode.SUCCESSS.getMsg(),this.tbMemberService.update(tbMember));
    }


    @GetMapping("selectByPhone")
    public Result selectByPhone(String phoneNum){
        //返回成功
        return this.tbMemberService.selectByPhone(phoneNum);
    }


    /**
     * 通过手机号修改密码
     * @return
     */
    @PutMapping("updateByPhone")
    public Result updateByPhone(String password, String phoneNum) {
        return new Result(ReturnCode.SUCCESSS.getCode(),
                ReturnCode.SUCCESSS.getMsg(),this.tbMemberService.updateByPhone(password,phoneNum));
    }


    @GetMapping("memberLogin")
    public Result memberLogin(String phone, String password){
        return this.tbMemberService.memberLogin(phone,password);
    }

    /**
     * 获取验证码
     * @param phoneNum
     * @return
     */
    @GetMapping("getCode")
    public String getCode(String phoneNum){
        Random r  =new Random();
        String verifyCode = String.valueOf(new Random().nextInt(900000) + 100000);
        try {
            String code = testSms.sentSms(phoneNum,verifyCode);
            return verifyCode;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 更新
     * @param tbMember
     * @return
     */
    @PutMapping("update")
    public Result update(@RequestBody TbMember tbMember){
        return new Result(ReturnCode.SUCCESSS.getCode(),
                ReturnCode.SUCCESSS.getMsg(),this.tbMemberService.update(tbMember));
    }

    @GetMapping ("exportExcel")
    public String exportExcel(HttpServletResponse response) throws IOException {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyyMMdd hhmmss");
        String sheetName="用户信息";
        // 初始化数据
        List<TbMember> clientList = tbMemberService.queryAll(null);
        /*FileOutputStream out = null;
        //获取配置文件中保存对应excel文件的路径，本地也可以直接写成F：excel/testExcel
        String folderPath = ResourceBundle.getBundle("application").getString("downloadFolder") + File.separator + "testExcel";
        System.out.println(folderPath);
        //创建上传文件目录
        File folder = new File(folderPath);
        //如果文件夹不存在创建对应的文件夹
        if (!folder.exists()) {
            folder.mkdirs();
        }*/
        //设置文件名
        String fileName = sdf1.format(new Date()) + sheetName + ".xls";
        // String savePath = folderPath + File.separator + fileName;
        response.setHeader("content-disposition",
                "attachment;fileName="+fileName);


//        try {
//            out = new FileOutputStream(savePath);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        ExcelUtil<TbMember> util = new ExcelUtil<TbMember>(TbMember.class); // 创建工具类.
        util.exportExcel(clientList, sheetName ,65536, response.getOutputStream()); // 导出
        System.out.println("----执行完毕----------");
        // System.out.println(savePath);
        //返回文件保存全路径
        return fileName;
    }
    @PostMapping ("importExcel")
    public String importExcel(@RequestParam("file") MultipartFile file){


        InputStream is =null;
        try {
            // @RequestParam("file") MultipartFile file 是用来接收前端传递过来的文件

            is = file.getInputStream();
            //下面是自己测试
            /*is = new FileInputStream("D:\\Poi测试\\会员测试.xls");*/

        } catch (IOException e) {
            e.printStackTrace();
        }
        ExcelUtil excelUtil=new ExcelUtil(TbMember.class);
        List list = excelUtil.importExcel("用户信息", is);
        int n=0;
        for (int i=0;i<list.size();i++){
            TbMember client= (TbMember) list.get(i);
            System.out.println(client);
            n= tbMemberService.insertBy(client);
            System.out.println("i值为："+list.get(i));
        }
        if (n>0){
            return "success";
        }
        return "失败";
    }
}